<script setup lang="ts">
import {onMounted, ref} from "vue";
import {useUserStore} from "@/stores/userStore.js";
import {ElMessage, UploadProps} from "element-plus";
import {modifyUserAPI} from "@/apis/userManage.js";
import router from "@/router/index.js";


const userInfoStore=useUserStore();

interface userType {
  id:number,
  loginName:string,
  realName:string,
  phone:string,
  email:string,
  createTime:number,
  updateTime:number,
  profilephoto:string,
  password:string,
  confirmPassword:string,
}

const userDetail=ref<userType>({
  id:0,
  loginName:'',
  realName:'',
  phone:'',
  email:'',
  createTime:0,
  updateTime:0,
  profilephoto:'',
  password:'',
  confirmPassword:''
});

onMounted(async () => {
  userDetail.value=userInfoStore.userDetails;
})


const showInfoFlg=ref(true)
const showUpdateFlg=ref(false);

const switchStatus=()=>{
  showInfoFlg.value=!showInfoFlg.value;
  showUpdateFlg.value=!showUpdateFlg.value;
}



// 时间戳变成真实时间
function getDate(time: number) {
  let date = new Date(time);
  let Y=date.getFullYear()+'年';
  let M=(date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '月';
  let D=date.getDate()+'日';
  let h=date.getHours()+'时';
  let m=date.getMinutes()+'分';
  return Y+M+D+h+m;
}

const photoFlag=ref(false);
// 注意，定义一个File类型的ref变量，应该这样子描述
const phototemp=ref<File>();

// 控制提交按钮的可操作性
const disableSwitch=ref(false);

// 删除头像的操作
const handleRemove=()=>{
  phototemp.value=undefined;
}

// 用于判断文件大小是否合法，限制重复上传的作用及文件类型
const handleChange: UploadProps['onChange'] = (file,fileList) => {
  //1、判断文件大小是否合法，文件限制不能大于100M===测试暂定是10000，后期改回来
  const fileSizeLimit = (file.size) / 1024 / 1024 < 200;
  if (!fileSizeLimit) {
    ElMessage({
      type: 'error',
      message: '上传文件大小不能超过 200MB!',
    })
    return false;
  }
  else {
    // formData.append('profilePhoto',file.raw);
    photoFlag.value=true;
    phototemp.value=file.raw;
  }
}
const formData=new FormData();
const modifyOneSummit=async ()=>{
  formData.append('id',userDetail.value.id);
  formData.append('loginName',userDetail.value.loginName);
  formData.append('realName',userDetail.value.realName);
  formData.append('phone',userDetail.value.phone);
  formData.append('email',userDetail.value.email);
  if (phototemp.value!==undefined)
  {
    formData.append('profilePhoto',phototemp.value);
    console.log("图片修改");
  }

//   如果其中一个密码为空，就不修改密码,修改其它信息
  if(userDetail.value.password===null || userDetail.value.confirmPassword === null|| userDetail.value.password.trim()==='' || userDetail.value.confirmPassword.trim()===''){
    console.log("1");
    const res=  await modifyUserAPI(formData);
    if(res.code===200){
      ElMessage({
        type:'success',
        message:'修改成功',
      })

    }
    else {
      ElMessage({
        type:'error',
        message:'修改失败',
      })
    }
    showInfoFlg.value=true;
    window.location.reload();

  }

// 如果两个密码都不为空，就修改密码
  else if(userDetail.value.password.trim()!==userDetail.value.confirmPassword.trim()){
    console.log("2");
    ElMessage({
      type:'error',
      message:'两次密码不一致',
    })
     window.location.reload();
    return;
  }
  else {
    formData.append('password',userDetail.value.password.trim());
    const res=  await modifyUserAPI(formData);
    if(res.code===200){
      ElMessage({
        type:'success',
        message:'修改成功',
      })
      await router.push("/userInfo");
    }
    else {
      ElMessage({
        type:'error',
        message:'修改失败',
      })

    }
    showInfoFlg.value=true;
    window.location.reload();
  }

}


</script>

<template>
  <!-- 面包屑 -->
  <div class="bread-container">
    <el-breadcrumb separator=">">
      <el-breadcrumb-item :to="{ path: `/` }">首页</el-breadcrumb-item>
      <el-breadcrumb-item  >用户详细页</el-breadcrumb-item>
    </el-breadcrumb>
  </div>

  <div class="divTable">
    <table class="table">
      <tbody>
      <tr>
        <td class="tableTitle" colspan="4" >用户信息</td>
      </tr>
      <tr>
        <td style="width: 250px;height: 15px;text-align: center;background: #EFF6FF;color: #242424;font-family: 微软雅黑,serif">账号登录名称</td>
        <td style="width: 350px;height: 15px;   text-align: center  "> {{userDetail.loginName}} </td>
        <td style="width: 250px;height: 15px; text-align: center ;background: #EFF6FF"  >真实姓名</td>
        <td style="width: 350px;height: 15px ; text-align: center   "><span v-show="showInfoFlg">{{
            userDetail.realName
          }}</span> <el-input v-model="userDetail.realName" v-show="showUpdateFlg"/> </td>
      </tr>
      <tr>
        <td style="width: 250px;height: 15px;text-align: center;background: #EFF6FF">联系电话</td>
        <td style="width: 350px;height: 15px;text-align: center  "><span v-show="showInfoFlg">{{ userDetail.phone }}</span> <el-input v-model="userDetail.phone" v-show="showUpdateFlg"/></td>
        <td style="width: 250px;height: 15px;text-align: center ;background: #EFF6FF"  >电子邮箱</td>
        <td style="width: 350px;height: 15px;text-align: center   "><span v-show="showInfoFlg">{{ userDetail.email }}</span> <el-input v-model="userDetail.email" v-show="showUpdateFlg"/></td>
      </tr>
      <tr v-show="showUpdateFlg">
        <td style="width: 250px;height: 15px;text-align: center;background: #EFF6FF">密码</td>
        <td style="width: 350px;height: 15px;text-align: center  "><el-input type="password" show-password v-model="userDetail.password" v-show="showUpdateFlg"/></td>
        <td style="width: 250px;height: 15px;text-align: center ;background: #EFF6FF"  >确认密码</td>
        <td style="width: 350px;height: 15px;text-align: center   "><el-input type="password" show-password v-model="userDetail.confirmPassword" v-show="showUpdateFlg"/></td>
      </tr>

      <tr v-show="showInfoFlg">
        <td style="width: 250px;height: 15px;text-align: center;background: #EFF6FF">创建时间</td>
        <td style="width: 350px;height: 15px;text-align: center  ">{{ getDate(userDetail.createTime) }}</td>
        <td style="width: 250px;height: 15px;text-align: center ;background: #EFF6FF"  >最后修改时间</td>
        <td style="width: 350px;height: 15px;text-align: center   ">{{ getDate(userDetail.updateTime) }}</td>
      </tr>
      <!--==========================用户头像参考后台管理-->
      <tr v-show="!showUpdateFlg">
        <td style="width: 250px;height: 15px;text-align: center;background: #EFF6FF">用户头像</td>
        <td  colspan="3" style="width: 350px;height: 15px;text-align: center  ">
          <br>
          <div class="demo-image__preview">
            <el-image
                style="width: 100px; height: 100px"
                :src="userDetail.profilephoto"
                :zoom-rate="1.2"
                :max-scale="5"
                :min-scale="0.5"
                fit="cover"
            />
          </div>
        </td>
      </tr>
      <tr v-show="showUpdateFlg">
        <td colspan="4" style="background:#EFF6FF ">
          <el-upload
              class="upload-demo"
              ref="upload"
              action=""
              :auto-upload="false"
              :drag="false"
              :on-change="handleChange"
              :on-remove="handleRemove"
              accept=".jpeg,.gif,.jpg,.png,.bmp,"
          >

            <el-button :disabled="photoFlag" type="primary" style="width: 150px;" >请选择需要上传的文件</el-button>
            <template #tip>
              <div class="el-upload__tip">
                支持格式：.jpeg .jpg .png .bmp .gif ，单个文件不能超过200MB
              </div>
            </template>
          </el-upload>
        </td>
      </tr>

      <tr>
        <td colspan="4" style="text-align: center">
          <el-button v-show="showUpdateFlg" @click="modifyOneSummit">确认修改</el-button>
        </td>
      </tr>
      <tr>
        <td colspan="4" style="text-align: center">
          <el-button v-show="showInfoFlg" @click="switchStatus">修改用户信息</el-button>
        </td>
      </tr>
      </tbody>
    </table>
  </div>

  <!--  <el-button  @click="modifyOneSummit">确认修改</el-button>-->

</template>

<style scoped lang="scss">

.bread-container {
  padding: 25px 10px;
  margin-left: 10px;
}
.divTable {
  position: static;
  top: 150px;
  bottom: 0;
  left: 300px;
  right: 0;
  margin: 30px 30px 30px 30px;
}
table, td,tr{
  border: 1px solid #44a8da;
  text-align: center;
  border-spacing: 0;
  border-collapse: collapse;
  height: 45px;
}

.tableTitle{

  border-right: 0 none;
  border-left: 0 none;
  text-align: center;
  font-size: large;
  font-weight: bold;
}

.demo-image__error .image-slot {
  font-size: 30px;
}
.demo-image__error .image-slot .el-icon {
  font-size: 30px;
}
.demo-image__error .el-image {
  width: 100%;
  height: 200px;
}
</style>